package com.huanglejing.shanggou.service

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import com.huanglejing.mylibrary.KLog
import com.huanglejing.shanggou.rx.RxUtils
import com.huanglejing.shanggou.rx.SchedulersCompat
import rx.Subscription

/**
 * 倒计时service
 */
class CountDownService : Service() {

    private var binder: CountDownBinder? = null
    private var countDownCallBack: ICountDownCallBack? = null
    private var countDownSub: Subscription? = null

    override fun onBind(intent: Intent): IBinder? {
        return binder
    }

    override fun onCreate() {
        super.onCreate()
        KLog.d()
        binder = CountDownBinder()
    }

    override fun onDestroy() {
        super.onDestroy()
        countDownSub?.unsubscribe()
    }

    private fun countDown(time: Int) {
        countDownSub?.let {
            if (it.isUnsubscribed) it.unsubscribe()
        }
        KLog.d("start count down")
        countDownSub = RxUtils.countdown(time).compose(SchedulersCompat.computation<Int>()).subscribe({ integer -> countDownCallBack?.countDown(integer) }, { stopSelf() }) {
            countDownCallBack?.finishCountDown()
            stopSelf()
        }
    }

    interface ICountDownCallBack {
        //倒计时回调
        fun countDown(result: Int)

        fun finishCountDown()
    }

    inner class CountDownBinder : Binder() {
        fun start(time: Int) {
            countDown(time)
        }

        fun stop() {
            countDownSub?.unsubscribe()
            this@CountDownService.countDownCallBack?.finishCountDown()
        }

        fun setCountDownListener(callBack: ICountDownCallBack) {
            this@CountDownService.countDownCallBack = callBack
        }
    }
}
